package com.android.test.util;

import java.util.HashMap;
import java.util.LinkedList;

import com.android.test.R;
import com.android.test.model.IconPair;

import android.content.Context;
import android.graphics.drawable.Drawable;

public class IconCache {
    private static final String TAG = IconCache.class.getSimpleName();
    private static final int MAX_SIZE = 80;
    private static final int NORMAL_SIZE = 50;
    private static final HashMap<String, IconPair> sIconMap = new HashMap<String, IconPair>();

    private static final LinkedList<String> sIcons = new LinkedList<String>();
    private static Drawable mDefaultIcon;

    private static IconCache iconCacheInstance;

    public static IconCache getInstance() {
	synchronized (IconCache.class) {
	    if (iconCacheInstance == null) {
		iconCacheInstance = new IconCache();
	    }
	}

	return iconCacheInstance;
    }

    public Drawable getDefaultIcon(Context context) {
	synchronized (IconCache.class) {
	    if (mDefaultIcon == null) {
		mDefaultIcon = context.getResources().getDrawable(
			R.drawable.icon);
	    }
	}

	return mDefaultIcon;
    }

    public IconPair get(int orgId) {
	return get("org_icon_" + orgId);
    }

    public void put(int orgId, Drawable drawable) {
	put("org_icon_" + orgId, drawable);
    }

    public IconPair get(String url) {
	synchronized (sIconMap) {
	    IconPair pair = (IconPair) sIconMap.get(url);
	    if (pair != null) {
		if (pair.drawable != null) {
		    int index = sIcons.indexOf(url);
		    if (index == -1) {
			sIcons.add(0, url);
		    } else if (index > 0) {
			sIcons.remove(index);
			sIcons.add(0, url);
		    }
		}
	    } else {
		pair = new IconPair();
		sIconMap.put(url, pair);
	    }

	    return pair;
	}
    }

    public void put(String url, Drawable drawable) {
	if (url == null || drawable == null) {
	    return;
	}

	synchronized (sIconMap) {
	    IconPair pair = sIconMap.get(url);
	    if (pair == null) {
		pair = new IconPair();
	    }
	    if (pair.drawable == null) {
		pair.drawable = drawable;
		pair.miss = false;

		sIconMap.put(url, pair);
		sIcons.add(0, url);
		if (sIcons.size() > MAX_SIZE) {
		    try {
			for (; sIcons.size() > NORMAL_SIZE;) {
			    String key = sIcons.get(sIcons.size() - 1);
			    Drawable image = sIconMap.get(key).drawable;
			    image = null;
			    sIconMap.remove(key);
			    sIcons.remove(sIcons.size() - 1);
			}
		    } catch (Exception e) {
		    }
		}
	    } else {
		int index = sIcons.indexOf(url);
		if (index == -1) {
		    sIcons.add(0, url);
		} else if (index > 0) {
		    sIcons.remove(index);
		    sIcons.add(0, url);
		}
	    }
	}
    }

    public void clear() {
	sIconMap.clear();
	sIcons.clear();
    }
}
